package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;


@RestController
@RequestMapping("/common")
public class UplodaController {

    @Autowired
    private HttpServletResponse response;

    @Value("${imgURL.name}")
    private String url;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        //重新命名
        String newFileName = UUID.randomUUID().toString();
        //获取图片的后缀名
        String oldFileName = file.getOriginalFilename();
        String hzName = oldFileName.substring(oldFileName.lastIndexOf("."));
        newFileName = newFileName + hzName;
        //图片储存到服务器
        file.transferTo(new File(url + newFileName));
        return R.success(newFileName);
    }

    @GetMapping("/download")
    public void download(String name) throws IOException {
        //找到图片并且读取图片
        FileInputStream fis = new FileInputStream(url + name);
        //获得网络输出流
        ServletOutputStream os = response.getOutputStream();

        byte[] bytes = new byte[1024];
        while (true) {
            int len = fis.read(bytes);
            if (len == -1) {
                break;
            }
            os.write(bytes, 0, len);
        }
        os.close();
        fis.close();
    }
}
